package com.kanshu.ksgb.fastread.doudou.module.signin.activity

import android.animation.Animator
import android.animation.AnimatorInflater
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.View.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.gyf.barlibrary.ImmersionBar
import com.inmobi.ads.InMobiInterstitial
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.SignInBeanNew
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.SignInData
import com.kanshu.ksgb.fastread.doudou.common.business.event.TaskEvent
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.SignInResult
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterPresenter
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_base_layout.*
import kotlinx.android.synthetic.main.layout_new_dialog_sign_in.*
import org.greenrobot.eventbus.EventBus
import java.util.*


/**
 * Created by wcy on 18/6/20
 */
@Route(path = ARouterConfig.SIGN_IN_PAGE)
@SuppressLint("SetTextI18n")
class NewSignInActivity : BaseActivity() {
    // 补签次数
    var mSupplementCount = 0
    // 最大补签次数
    private var mMaxSupplementCount = 0
    // 签到数据
    lateinit var signInData: SignInData
    // 今天周几
    var toDayInWeek: Int = 0
    // 最后一次签到时间
    private var mLastSignWeek: Int = 0
    // 签到天数
    var signCount: Int = 0
    // 今天是否签到
    var signedToday: Boolean = false
    var phone = ""
    private lateinit var dayViews: Array<LinearLayout>
    lateinit var presenter: PersonCenterPresenter
    private var mRightOutSet: AnimatorSet? = null
    private var mLeftInSet: AnimatorSet? = null
    private var mRewardVideoAd: Any? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_new_dialog_sign_in)
        presenter = PersonCenterPresenter(lifeCyclerSubject)
        phone= StorageUtils.getPreference<String>(activity, Constants.SP_NAME, Constants.USER_BIND_PHONE + UserUtils.getUserId(), "")
        isLogin()
        goneTitlebar(true)
        front_close.setOnClickListener {
            finish()
        }
        behind_close.setOnClickListener { finish() }
        dayViews = arrayOf(sign_monday_l, sign_tuesday_l, sign_wednesday_l, sign_thursday_l, sign_friday_l, sign_saturday_l, sign_sunday_l)
        root.setBackgroundColor(resources.getColor(R.color.transparent))
        // 触摸事件
        sign_in_root.setOnTouchListener { _, p1 ->
            if (!Utils.isTouchPointInView(front, p1?.x?.toInt() ?: 0, p1?.y?.toInt() ?: 0)
                    && !Utils.isTouchPointInView(behind, p1?.x?.toInt() ?: 0, p1?.y?.toInt() ?: 0)
            ) {
                finish()
            }
            false
        }
        val data = intent.getParcelableExtra<SignInData>("data")
        if (data == null) {
            loadSignData()
        } else {
            initData(data)
        }

        play_video_btn.setOnClickListener {
            if (mRewardVideoAd != null) {
                when (mRewardVideoAd) {
                    is InMobiInterstitial -> (mRewardVideoAd as InMobiInterstitial).show()
                    is TTRewardVideoAd -> (mRewardVideoAd as TTRewardVideoAd).showRewardVideoAd(this@NewSignInActivity)
                    else -> ToastUtil.showMessage("广告还没有准备好，请稍候！")
                }
            } else {
                ToastUtil.showMessage("广告还没有准备好，请稍候！")
            }
        }
        /*  continue_day.setOnClickListener {
                   setAnimators(1, front, behind, true)
               }*/
    }

    private var mDayInWeek: Int = 0
    private fun loadAd(dayInWeek: Int) {
        mDayInWeek = dayInWeek
        AdUtils.fetchAdUtil(activity, null, null, ADConfigBean.POSITION_SIGN_IN, AdStyleBean.REWARDED_REWARDED_VIDEO_STYLE, 0, object : BaseAdListener {
            override fun onAdLoadSucceeded(view: View?) {
                videoAdPlayCompleted()
            }

            override fun onAdLoadFailed() {
                Log.d("wcy", "fail")
            }

            override fun onAdClicked() {
            }

            override fun onADClosed() {
            }

            override fun onBackAd(ad: Any) {
                mRewardVideoAd = ad
            }
        })
    }

    private fun videoAdPlayCompleted() {
        Log.d("wcy", "success")
        if (mMaxSupplementCount <= mSupplementCount) {
            ToastUtil.showMessage("亲，一周可补签$mMaxSupplementCount 次")
            return
        }
        if(!TextUtils.isEmpty(phone)){
            doSign(mDayInWeek, true)
        }
    }

    override fun onBeforeSetContentView() {
        if (isNeedRemoveWindowBackground) {
            window.setBackgroundDrawable(null)
        }
    }

    override fun isNeedRemoveWindowBackground(): Boolean {
        return false
    }

    @SuppressLint("ResourceType")
    private fun setAnimators(dayInWeek: Int, first: View, second: View, loadAd: Boolean) {
        val distance = 18000
        val scale = activity.resources.displayMetrics.density * distance
        first.cameraDistance = scale
        second.cameraDistance = scale
        mRightOutSet = AnimatorInflater.loadAnimator(activity, R.anim.card_flip_anim_out) as AnimatorSet
        mLeftInSet = AnimatorInflater.loadAnimator(activity, R.anim.card_filp_anim_in) as AnimatorSet
        mRightOutSet!!.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                first.visibility = INVISIBLE
                if (loadAd) {
                    loadAd(dayInWeek)
                }
            }
        })
        second.visibility = View.VISIBLE
        mRightOutSet?.setTarget(first)
        mLeftInSet?.setTarget(second)
        mRightOutSet?.start()
        mLeftInSet?.start()
    }

    private fun initData(data: SignInData) {
        this.signInData = data
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = signInData.other.current_time * 1000
        mMaxSupplementCount = signInData.other.max_supplement_num
        mLastSignWeek = signInData.other.week
        val dayInWeek = calendar.get(Calendar.DAY_OF_WEEK)
        toDayInWeek = NewSignInActivity.daysInWeek[dayInWeek - 1]
        signInData.lists?.forEach {
            if (it.signin == 1) {
                if (toDayInWeek == it.week) {
                    signedToday = true
                }
            }
        }
        mMaxSupplementCount = signInData.other.max_supplement_num
        mSupplementCount = signInData.other.supplement_num
        if (TextUtils.isDigitsOnly(signInData.other.residue_amount)) {
            pool_balance.text = String.format("当前分红池金额：%1$.1f元", signInData.other.residue_amount.toFloat() / 100)
        }
        signInData.lists.forEach {
            if (it.week < mLastSignWeek && it.signin == SignInBeanNew.UN_SIGN_IN) {
                it.signin = SignInBeanNew.SUPPLEMENT
            }
            if (it.signin == SignInBeanNew.SUPPLEMENT && it.week > toDayInWeek) {
                it.signin = SignInBeanNew.UN_SIGN_IN
            }
            if (it.signin == SignInBeanNew.SUPPLEMENT_SUCCESS) {
                it.signin = SignInBeanNew.SIGN_IN_SUCCESS
            }
            setSignStatus(it.week, it.signin)
        }
        continue_day.text = signInData.other.num
        // 签到今天数据
        if(!TextUtils.isEmpty(phone)){
            doSign(toDayInWeek, false)
        }
    }

    private fun isLogin(){
        if (!MMKVUserManager.getInstance().isUserLogin()) {
            ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "")
            finish()
        }
    }

    private fun loadSignData() {
        presenter.getSignData(object : BaseObserver<SignInData>() {
            override fun onResponse(listBaseResult: BaseResult<SignInData>, signInData: SignInData, disposable: Disposable) {
                initData(signInData)
            }
        })
    }

    override fun isSupportSwipeBack(): Boolean {
        return false
    }

    override fun onBackPressed() {
        finish()
    }

    override fun initStatusbar() {
        try {
            mImmersionBar = ImmersionBar.with(this)
            mImmersionBar!!.keyboardEnable(true)
            mImmersionBar!!.init()
            if (ImmersionBar.isSupportStatusBarDarkFont())
                mImmersionBar!!.statusBarDarkFont(true).init()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun doSign(dayInWeek: Int, isSupplement: Boolean) {
        if (toDayInWeek < dayInWeek) {
            return
        }
        presenter.doSign(dayInWeek, object : BaseObserver<SignInResult>() {
            override fun onResponse(stringBaseResult: BaseResult<SignInResult>, s: SignInResult, disposable: Disposable) {
                if (stringBaseResult.result.status.code == 0) {
                    signedToday = true
                    signCount = s.num
                    continue_day.text = signCount.toString()
                    sign_in_status.text = "签到成功 +" + s.beans
                    if (isSupplement) {
                        ToastUtil.showMessage("${daysInWeekStr[dayInWeek - 1]}补签成功")
                        setAnimators(dayInWeek, behind, front, false)
                        mSupplementCount++
                    }
                    sign_in_profit.text = "已获得" + s.all_beans + "金豆"
                    setSignStatus(dayInWeek, SignInBeanNew.SIGN_IN_SUCCESS)
                    EventBus.getDefault().post(TaskEvent(TaskEvent.SIGN_IN))
                }

            }

            override fun onError(code: Int, errDesc: String) {
                super.onError(code, errDesc)
                var beans = 0
                var allbeans = 0
                signInData.lists.forEach {
                    if (it.week <= toDayInWeek && it.signin >= SignInBeanNew.SIGN_IN_SUCCESS) {
                        beans = it.beans
                        allbeans += it.beans
                    }
                }
                // 太频繁 29998
                if (code == 29998) {
                    sign_in_status.text = "签到成功 +" + beans.toString()
                } else {
                    sign_in_status.text = "签到失败"
                }
                sign_in_profit.text = "已获得" + allbeans.toString() + "金豆"
            }
        })
    }

    private fun setSignStatus(dayInWeek: Int, signIned: Int) {
        val view = dayViews[dayInWeek - 1]
        val frameLayout = view.getChildAt(0) as FrameLayout
        val signStatusIcon = frameLayout.getChildAt(0) as ImageView
        val signStatusTxt = frameLayout.getChildAt(1)
        when (signIned) {
            SignInBeanNew.SIGN_IN_SUCCESS -> {
                signStatusTxt.visibility = GONE
                signStatusIcon.visibility = VISIBLE
                view.setBackgroundResource(R.mipmap.ic_sign_in_success)
                if (dayInWeek == 7) {
                    view.setBackgroundResource(R.mipmap.ic_sign_in_success_long)
                }
                signStatusIcon.setImageResource(R.mipmap.ic_sign_in_completed)
                view.setOnClickListener(null)
            }
            SignInBeanNew.UN_SIGN_IN -> {
                view.setBackgroundResource(R.mipmap.ic_sign_in_unfinished)
                if (dayInWeek == 7) {
                    view.setBackgroundResource(R.mipmap.ic_sign_in_unfinish_long)
                }
                signStatusTxt.visibility = VISIBLE
                signStatusIcon.visibility = GONE
                view.setOnClickListener { doSign(dayInWeek, false) }
            }
            SignInBeanNew.SUPPLEMENT -> {
                val config = ADConfigs.showAD(ADConfigBean.POSITION_SIGN_IN.toString())
                if (config == null) {
                    view.setBackgroundResource(R.mipmap.ic_sign_in_unfinished)
                    if (dayInWeek == 7) {
                        view.setBackgroundResource(R.mipmap.ic_sign_in_unfinish_long)
                    }
                    signStatusTxt.visibility = VISIBLE
                    signStatusIcon.visibility = GONE
                    view.setOnClickListener { doSign(dayInWeek, false) }
                } else {
                    view.setBackgroundResource(R.mipmap.ic_sign_in_success)
                    if (dayInWeek == 7) {
                        view.setBackgroundResource(R.mipmap.ic_sign_in_success_long)
                    }
                    signStatusTxt.visibility = GONE
                    signStatusIcon.visibility = VISIBLE
                    signStatusIcon.setImageResource(R.mipmap.ic_sign_in_wait)
                    view.setOnClickListener { doSupplement(dayInWeek) }
                }

            }
        }
        val sunDayLock = signCount == 7
        if (sunDayLock) {
            sign_sunday_tip.text = "解锁分红资格"
            dayViews[6].setBackgroundResource(R.mipmap.ic_sign_in_success_long)
            dayViews[6].setOnClickListener {
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_PROFIT)
            }
        }
    }

    private fun doSupplement(dayInWeek: Int) {
        if (mSupplementCount < mMaxSupplementCount) {
            setAnimators(dayInWeek, front, behind, true)
        } else {
            ToastUtil.showMessage("亲，一周可补签$mMaxSupplementCount 次")
        }
    }

    override fun onPause() {
        overridePendingTransition(0, 0)
        super.onPause()
    }

    companion object {
        @JvmStatic
        val daysInWeek = intArrayOf(7, 1, 2, 3, 4, 5, 6)
        @JvmStatic
        val daysInWeekStr = mutableListOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mRewardVideoAd != null) {
            mRewardVideoAd = null
        }
    }
}
